package com.platform.mall.security.config;

import com.platform.mall.common.annotation.AnonymousAccess;
import com.platform.mall.security.filter.PLAuthenticationTokenFilter;
import com.platform.mall.security.handler.EntryPointUnauthorizedHandler;
import com.platform.mall.security.handler.RestAccessDeniedHandler;
import com.platform.mall.security.provider.SysUserAuthenticationProvider;
import com.platform.mall.security.provider.UserMemberAuthenticationProvider;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.factory.PasswordEncoderFactories;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.mvc.method.RequestMappingInfo;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;

import javax.annotation.Resource;
import java.util.*;


@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Resource
    private  PLAuthenticationTokenFilter plAuthenticationTokenFilter;
    @Resource
    private  EntryPointUnauthorizedHandler entryPointUnauthorizedHandler;
    @Resource
    private  RestAccessDeniedHandler restAccessDeniedHandler;
    @Resource
    private ApplicationContext applicationContext;
    @Resource
    @Qualifier("userMemberDetailsService")
    private  UserDetailsService userDetailsService;
    @Resource
    @Qualifier("sysUserDetailsService")
    private  UserDetailsService managerDetailsService;

    /**
     * 注入UserMemberAuthenticationProvider
     *
     * @return
     */
    @Bean("UserMemberAuthenticationProvider")
    DaoAuthenticationProvider daoUserAuthenticationProvider() {
        return new UserMemberAuthenticationProvider(encoder(), userDetailsService);
    }


    /**
     * 注入SysUserAuthenticationProvider
     *
     * @return
     */
    @Bean("SysUserAuthenticationProvider")
    DaoAuthenticationProvider daoMangerAuthenticationProvider() {
        return new SysUserAuthenticationProvider(encoder(), managerDetailsService);
    }

    /**
     * 向AuthenticationManager添加Provider
     *
     * @return
     */
    @Resource
    public void configureGlobal(AuthenticationManagerBuilder auth) {
        auth.authenticationProvider(daoUserAuthenticationProvider());
        auth.authenticationProvider(daoMangerAuthenticationProvider());
    }


    @Resource
    public void configureAuthentication(AuthenticationManagerBuilder authenticationManagerBuilder) throws Exception {
        authenticationManagerBuilder.userDetailsService(this.userDetailsService).passwordEncoder(encoder());
    }

    /**
     * 注入AuthenticationManager
     *
     * @return
     */
    @Bean
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    /**
     * 注入PasswordEncoder
     *
     * @return
     */
    @Bean
    public PasswordEncoder encoder() {
        PasswordEncoder encoder =
                PasswordEncoderFactories.createDelegatingPasswordEncoder();
        return encoder;
    }


    /**
     * 具体Security 配置
     *
     * @return
     */
    @Override
    protected void configure(HttpSecurity http) throws Exception {

        // 搜寻匿名标记 url： @AnonymousAccess
        RequestMappingHandlerMapping requestMappingHandlerMapping = (RequestMappingHandlerMapping) applicationContext.getBean("requestMappingHandlerMapping");
        Map<RequestMappingInfo, HandlerMethod> handlerMethodMap = requestMappingHandlerMapping.getHandlerMethods();
        // 获取匿名标记
        Set<String> anonymousUrls = getAnonymousUrl(handlerMethodMap);

        http.
                csrf().disable().//默认开启，这里先显式关闭csrf
                //Spring Security永远不会创建HttpSession，它不会使用HttpSession来获取SecurityContext
                sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                .authorizeRequests()
                .antMatchers(HttpMethod.OPTIONS, "/**").permitAll() //任何用户任意方法可以访问/**
                .antMatchers("/auth/**","/captcha").permitAll() //任何用户可以访问/user/**
                .antMatchers("/swagger/**").permitAll()
                .antMatchers("/swagger-ui.html").permitAll()
                .antMatchers("/webjars/**").permitAll()
                .antMatchers("/v2/**").permitAll()
                .antMatchers("/v2/api-docs-ext/**").permitAll()
                .antMatchers("/swagger-resources/**").permitAll()
                .antMatchers("/doc.html").permitAll()
                .antMatchers(anonymousUrls.toArray(new String[0])).permitAll()
                .anyRequest().authenticated() //任何没有匹配上的其他的url请求，只需要用户被验证
                .and()
                .headers().cacheControl();
        http.addFilterBefore(plAuthenticationTokenFilter, UsernamePasswordAuthenticationFilter.class);
        http.exceptionHandling()
                .authenticationEntryPoint(entryPointUnauthorizedHandler)
                .accessDeniedHandler(restAccessDeniedHandler);
    }

    private Set<String> getAnonymousUrl(Map<RequestMappingInfo, HandlerMethod> handlerMethodMap) {
        Set<String> anonymousUrls = new HashSet<>();
        for (Map.Entry<RequestMappingInfo, HandlerMethod> infoEntry : handlerMethodMap.entrySet()) {
            HandlerMethod handlerMethod = infoEntry.getValue();
            AnonymousAccess anonymousAccess = handlerMethod.getMethodAnnotation(AnonymousAccess.class);
            if (null != anonymousAccess) {
                List<RequestMethod> requestMethods = new ArrayList<>(infoEntry.getKey().getMethodsCondition().getMethods());
                anonymousUrls.add(requestMethods.get(0).name());
            }
        }
        return anonymousUrls;
    }

}
